package com.hmall.item.controller;


import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmall.common.domain.PageDTO;

import com.hmall.item.domain.dto.ItemDTO;
import com.hmall.item.domain.po.Item;
import com.hmall.item.domain.po.ItemDoc;
import com.hmall.item.domain.query.ItemPageQuery;
import com.hmall.item.service.IItemService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Api(tags = "搜索相关接口")
@RestController
@RequestMapping("/search")
@RequiredArgsConstructor
public class SearchController {

    private final IItemService itemService;
    private final RestHighLevelClient restHighLevelClient;
    @ApiOperation("搜索商品")
    @GetMapping("/list")
    public PageDTO<ItemDoc> search(ItemPageQuery query) throws IOException {
        SearchRequest searchRequest = new SearchRequest("items");
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        if(StrUtil.isNotBlank(query.getKey())){
            boolQueryBuilder.must(QueryBuilders.matchQuery("name", query.getKey()));
        }
        if(StrUtil.isNotBlank(query.getBrand())){
            boolQueryBuilder.filter(QueryBuilders.termQuery("brand", query.getBrand()));
        }
        if(StrUtil.isNotBlank(query.getCategory())){
            boolQueryBuilder.filter(QueryBuilders.matchQuery("category", query.getCategory()));
        }
        if(query.getMaxPrice()!= null){
            boolQueryBuilder.filter(QueryBuilders.rangeQuery("price").lte(query.getMaxPrice()).gte(query.getMinPrice()));
        }
        searchRequest.source().query(boolQueryBuilder).size(query.getPageSize()).from(query.from());
        // todo change
        List<OrderItem> orders = query.toMpPage("updateTime", false).orders();
        for(OrderItem orderItem:orders){
            searchRequest.source().sort(orderItem.getColumn(),orderItem.isAsc()? SortOrder.ASC:SortOrder.DESC);
        }
        SearchResponse response = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
        SearchHits responseHits = response.getHits();
        long value = responseHits.getTotalHits().value;
        long  pages=query.getPageNo();
        SearchHit[] hits = responseHits.getHits();
        List<ItemDoc> itemDocs = new ArrayList<>();
        if(itemDocs !=null){
            for(SearchHit hit:hits){
                ItemDoc itemDoc = JSONUtil.toBean(hit.getSourceAsString(), ItemDoc.class);
                itemDocs.add(itemDoc);
            }
        }
        return new PageDTO<>(pages,value,itemDocs);
    }
//    // 分页查询
//    Page<Item> result = itemService.lambdaQuery()
//            .like(StrUtil.isNotBlank(query.getKey()), Item::getName, query.getKey())
//            .eq(StrUtil.isNotBlank(query.getBrand()), Item::getBrand, query.getBrand())
//            .eq(StrUtil.isNotBlank(query.getCategory()), Item::getCategory, query.getCategory())
//            .eq(Item::getStatus, 1)
//            .between(query.getMaxPrice() != null, Item::getPrice, query.getMinPrice(), query.getMaxPrice())
//            .page(query.toMpPage("update_time", false));
//    // 封装并返回
    //return PageDTO.of(result, ItemDTO.class);
}
